package data

import (
	"crypto/rand"
	"crypto/sha1"
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"log"
)

type DbUser struct {
	gorm.Model
	Uuid  string `gorm:"type:varchar(64)"`
	Name  string `gorm:"type:varchar(255)"`
	Email string `gorm:"type:varchar(255)"`
	Pswd  string `gorm:"type:varchar(255)"`
}

func (DbUser) TableName() string {
	return "users"
}

type DbSession struct {
	gorm.Model
	Uuid   string `gorm:"type:varchar(64)"`
	Email  string `gorm:"type:varchar(255)"`
	UserId uint
}

func (DbSession) TableName() string {
	return "sessions"
}

type DbThread struct {
	gorm.Model
	Uuid   string `gorm:"type:varchar(64)"`
	Topic  string `gorm:"type:text"`
	UserId uint
}

func (DbThread) TableName() string {
	return "threads"
}

type DbPost struct {
	gorm.Model
	Uuid     string `gorm:"type:varchar(64)"`
	Body     string `gorm:"type:text"`
	UserId   uint
	ThreadId uint
}

func (DbPost) TableName() string {
	return "posts"
}

var Gorm *gorm.DB

func init() {
	var err error
	Gorm, err = gorm.Open("mysql", "fancy:linuxfj1010@/fancy_web?charset=utf8&parseTime=True&loc=Local")
	if err != nil {
		panic(err)
	}

	Gorm.AutoMigrate(&DbUser{})
	Gorm.AutoMigrate(&DbSession{})
	Gorm.AutoMigrate(&DbThread{})
	Gorm.AutoMigrate(&DbPost{})
}

func createUUID() string {
	u := new([16]byte)
	_, err := rand.Read(u[:])
	if err != nil {
		log.Fatalln("Cannot generate UUID", err)
	}

	u[8] = (u[8] | 0x40) & 0x7F
	u[6] = (u[6] & 0xF) | (0x4 << 4)
	uuid := fmt.Sprintf("%x-%x-%x-%x-%x", u[0:4], u[4:6], u[6:8], u[8:10], u[10:])
	return uuid
}

func Encrypt(plain string) (crypt string) {
	crypt = fmt.Sprintf("%x", sha1.Sum([]byte(plain)))
	return
}
